import { ref, computed } from 'vue'
import { defineStore } from 'pinia'

export const useUserStore = defineStore('user', () => {

    const kong = {
        tel: '',
        name: '',
        carphoto: '',
        carid: '',
        password: '',
        cartype: '',
        idcode: '',
    }

    const userInfo = ref(JSON.parse(localStorage.getItem('userInfo')) || { ...kong })

    const userList = ref(JSON.parse(localStorage.getItem('userList')) || [])

    function setusertoLocal() {
        localStorage.setItem('userInfo', JSON.stringify(userInfo.value))
        localStorage.setItem('userList', JSON.stringify(userList.value))
    }

    function adduser(data) {
        userList.value.push(data)
        setusertoLocal()
    }

    function setuser(data) {
        userInfo.value = { ...data }
        setusertoLocal()
    }

    function isTelinList(tel) {
        for (let i = 0; i < userList.value.length; i++) {
            // console.log(userList.value[i]);
            if (userList.value[i].tel == tel) {
                return false
            }
        }
        return true
    }

    function setUserInfo(tel) {
        for (let i = 0; i < userList.value.length; i++) {
            // console.log(userList.value[i]);
            if (userList.value[i].tel == tel) {
                userInfo.value = { ...userList.value[i] }
                setusertoLocal()
                break
            }
        }
    }

    function loginForPassword(data) {
        for (let i = 0; i < userList.value.length; i++) {
            if (userList.value[i].tel == data.tel) {
                if (userList.value[i].password == data.password) {
                    userInfo.value = { ...userList.value[i] }
                    setusertoLocal()
                    return true
                }
                else {
                    return false
                }
            }
        }
    }

    function setNewPassword(data) {
        for (let i = 0; i < userList.value.length; i++) {
            if (userList.value[i].tel == data.tel) {
                userList.value[i].password = data.password
                userInfo.value = { ...kong }
                break
            }
        }
        setusertoLocal()
    }

    return {
        userInfo,
        userList,
        setuser,
        adduser,
        isTelinList,
        setUserInfo,
        loginForPassword,
        setNewPassword,
    }
})